import {messages} from "share/common";
import React from 'react'
import { connect } from 'react-redux'


import menuRoute from 'routes/menuRoute'
import { Form, Input, Row, Col, Select, Button, message, InputNumber } from 'antd'
const FormItem = Form.Item;
const Option = Select.Option;

import strategyService from 'containers/budget-setting/budget-organization/budget-strategy/budget-strategy.service'
import 'styles/budget-setting/budget-organization/budget-strategy/new-budget-strategy-detail.scss'

class NewBudgetStrategyDetail extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      controlMethodNotice: '',
      controlMethodOptions: [],
      messageCodeOptions: [],
      controlMethodValue: '',
      budgetStrategyDetail:  menuRoute.getRouteItem('budget-strategy-detail','key'),    //控制策略详情
    }
  }

  componentDidMount(){
    this.getSystemValueList(2005).then(res => { //预算控制方法
      let controlMethodOptions = res.data.values;
      this.setState({ controlMethodOptions })
    });
    strategyService.getMessages(2022).then(res => { //预算控制消息
      let messageCodeOptions = res.data;
      this.setState({ messageCodeOptions })
    });
  }

  handleSave = (e) =>{
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        values.controlStrategyId = this.props.params.strategyId;
        if (values.controlMethod !== 'NO_MESSAGE' && !values.messageCode) {
          message.error(messages('budget-setting.key149'/*请选择消息*/));
          return;
        }
        this.setState({loading: true});
        strategyService.newStrategyDetail(values).then(res=>{
          if(res.status === 200){
            this.setState({loading: false});
            message.success(messages('common.create.success',{name: ''}) /* 新建成功 */);
            this.handleCancel();
          }
        }).catch((e)=>{
          this.setState({loading: false});
          message.error(`${messages('common.create.filed') /* 新建失败 */}, ${e.response.data.message}`);
        })
      }
    });
  };

  handleCancel = () => {
    this.context.router.push(this.state.budgetStrategyDetail.url.replace(':id', this.props.params.id).replace(':strategyId', this.props.params.strategyId));
  };

  handleMethodChange = (value) => {

    let controlMethodNotice = '';
    if(value === 'BLOCK') {
      controlMethodNotice = messages('budget-setting.key150'/*如果满足触发条件，当单据提交时，禁止提交*/);
    } else if(value === 'ALLOWED') {
      controlMethodNotice = messages('budget-setting.key151'/*如果满足触发条件，当单据提交时，进行提示*/);
    } else {
      controlMethodNotice = messages('budget-setting.key152'/*不做任何控制*/);
      this.props.form.setFieldsValue({messageCode: null})
    }
    this.setState({ controlMethodNotice, controlMethodValue: value })
  };

  render() {
    const { getFieldDecorator } = this.props.form;

    const { controlMethodNotice, controlMethodOptions, messageCodeOptions, controlMethodValue } = this.state;
    return (
      <div className="new-budget-strategy-detail">
        <Form onSubmit={this.handleSave}>
          <Row>
            <Col span={7}>
              <FormItem label={messages('common.sequence')/*序号*/}>
                {getFieldDecorator('detailSequence', {
                  rules: [{
                    required: true,
                    message: messages('common.please.enter')/*请输入*/
                  }],
                  initialValue: ''
                })(
                  <InputNumber min={0}
                               precision={0}
                               placeholder={messages('common.please.enter')/*请输入*/}
                               style={{width:'100%'}}/>
                )}
              </FormItem>
            </Col>
            <Col span={7} offset={1}>
              <FormItem label={messages('budget-setting.key143'/*规则代码*/)}>
                {getFieldDecorator('detailCode', {
                  rules: [{
                    required: true,
                    message: messages('common.please.enter')/*请输入*/
                  }],
                  initialValue: ''
                })(
                  <Input placeholder={messages('common.please.enter')/*请输入*/} />
                )}
              </FormItem>
            </Col>
            <Col span={7} offset={1}>
              <FormItem label={messages('budget-setting.key36'/*控制策略*/)} help={controlMethodNotice}>
                {getFieldDecorator('controlMethod', {
                  rules: [{
                    required: true,
                    message: messages('common.please.enter')/*请输入*/
                  }]})(
                  <Select onChange={this.handleMethodChange} placeholder={messages('common.please.enter')/*请输入*/}>
                    {controlMethodOptions.map((option)=>{
                      return <Option key={option.value}>{option.messageKey}</Option>
                    })}
                  </Select>
                )}
              </FormItem>
            </Col>
          </Row>
          <Row>
            <Col span={7}>
              <FormItem label={messages('budget-setting.key144'/*控制规则名称*/)}>
                {getFieldDecorator('detailName', {
                  rules: [{
                    required: true,
                    message: messages('common.please.enter')/*请输入*/
                  }],
                  initialValue: ''
                })(
                  <Input placeholder={messages('common.please.enter')/*请输入*/} />
                )}
              </FormItem>
            </Col>
            <Col span={7} offset={1}>
              <FormItem label={
                <span>
                  {messages('budget-setting.key145'/*消息*/)}
                  <span className='default-color-font'>({messages('budget-setting.key234')/*可在值列表[预算控制消息]中自定义*/})</span>
                </span>
              }>
                {getFieldDecorator('messageCode', {
                  rules: [{
                    required: !(controlMethodValue === 'NO_MESSAGE'),
                    message: messages('common.please.select')/*请选择*/
                  }]})(
                  <Select placeholder={messages('common.please.select')/*请选择*/} disabled={controlMethodValue === 'NO_MESSAGE'}>
                    {messageCodeOptions && messageCodeOptions.map((option)=>{
                      return <Option key={option.value}>{option.messageKey}</Option>
                    })}
                  </Select>
                )}
              </FormItem>
            </Col>
            <Col span={7} offset={1}>
              <FormItem label={messages('budget-setting.key146'/*事件*/)}>
                {getFieldDecorator('expWfEvent', {
                  initialValue: ''
                })(
                  <Input placeholder={messages('common.please.enter')/*请输入*/} />
                )}
              </FormItem>
            </Col>
          </Row>
          <div>
            <Button type="primary" htmlType="submit" loading={this.state.loading}>{messages('common.save')/*保存*/}</Button>
            <Button className="btn-cancel" onClick={this.handleCancel}>{messages('common.cancel')/*取消*/}</Button>
          </div>
        </Form>
      </div>
    )
  }
}

NewBudgetStrategyDetail.contextTypes={
  router:React.PropTypes.object
};

function mapStateToProps(state) {
  return { }
}

const WrappedNewBudgetStrategyDetail = Form.create()(NewBudgetStrategyDetail);

export default connect(mapStateToProps)(WrappedNewBudgetStrategyDetail);

